package cn.com.dpc;

import java.lang.reflect.Field;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.dpc.bean.TreeBean;
import cn.com.dpc.bean.User;
import cn.com.dpc.util.DataService;
import cn.com.dpc.util.HttpGet;
import cn.com.dpc.util.SearchSuggestionSampleProvider;
import cn.com.dpc.util.TreeViewAdapter;

public class DataActivity extends Activity {
	private static int NOTIFICATION_ID = 0;

	int notification_id = 1;
	NotificationManager nm;
	Notification notification;

	ExpandableListView expandableList;
	TreeViewAdapter adapter;
	Button btnNormal, btnSuper;
	// Sample data set. children[i] contains the children (String[]) for
	// groups[i].
	public String[] groups = { "xxxx好友", "xxxx同学", "xxxxx女人" };
	public String[][] child = { { "A君", "B君", "C君", "D君" },
			{ "同学甲", "同学乙", "同学丙" }, { "御姐", "萝莉" } };

	public TreeBean[] districts;
	public TreeBean[][] stations;

	public String districtList = "";

	private String ipStr = "218.249.218.105";
	private String userId = "";
	private String password = "";
	private String result = "";

	public AlertDialog registerdialog = null;
	public ProgressDialog m_Dialog = null;

	private String sbStations = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.data);

		// Bundle bundle = getIntent().getExtras();
		// districtList = bundle.getString("districtList").trim();

		ImageButton editButton = (ImageButton) findViewById(R.id.edit_button);
		editButton.setVisibility(View.INVISIBLE);
		ImageButton backButton = (ImageButton) findViewById(R.id.back_button);
		backButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// doExit();

				new AlertDialog.Builder(DataActivity.this)
						.setTitle("提示")
						.setMessage("确定要退出监控系统吗？")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									public void onClick(
											DialogInterface dialoginterface,
											int i) {
										DataActivity.this.finish();
									}
								})
						.setNeutralButton("取消",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface arg0,
											int arg1) {
									}

								}).show();

				// DataActivity.this.finish();
			}
		});

		TextView titleText = (TextView) findViewById(R.id.myTitle);
		titleText.setText("动力源动环监控系统");

		adapter = new TreeViewAdapter(this, TreeViewAdapter.PaddingLeft >> 1);
		expandableList = (ExpandableListView) DataActivity.this
				.findViewById(R.id.ExpandableListView01);

		// adapter.RemoveAll();
		// adapter.notifyDataSetChanged();
		//
		// List<TreeViewAdapter.TreeNode> treeNode = adapter.GetTreeNode();
		// for (int i = 0; i < groups.length; i++) {
		// TreeViewAdapter.TreeNode node = new TreeViewAdapter.TreeNode();
		// node.parent = groups[i];
		// for (int ii = 0; ii < child[i].length; ii++) {
		// node.childs.add(child[i][ii]);
		// }
		// treeNode.add(node);
		// }
		//
		// adapter.UpdateTreeNode(treeNode);
		// expandableList.setAdapter(adapter);
		// expandableList.setOnChildClickListener(new OnChildClickListener() {
		//
		// @Override
		// public boolean onChildClick(ExpandableListView arg0, View arg1,
		// int parent, int children, long arg4) {
		//
		// String str = "parent id:" + String.valueOf(parent)
		// + ",children id:" + String.valueOf(children);
		// Toast.makeText(DataActivity.this, str, 300).show();
		// return false;
		// }
		// });

		showList();

		initNoti();

		nm.cancel(notification_id);
	}

	private void showList() {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... arg0) {
				try {
					Log.v("dpc.DataActivity", districtList);
					String dataStr = DataService.queryData(DataActivity.this);
					JSONArray jsonAll = new JSONArray();

					JSONObject jsonObject = new JSONObject(dataStr);
					districts = new TreeBean[jsonObject.getInt("disNum")];
					stations = new TreeBean[jsonObject.getInt("disNum")][jsonObject
							.getInt("staNum")];
					JSONArray jsonArray = jsonObject.getJSONArray("datas");
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jo = jsonArray.getJSONObject(i);
						TreeBean treeBean = new TreeBean();
						treeBean.setId(jo.getInt("did"));
						treeBean.setName(jo.getString("disName"));
						districts[i] = treeBean;

						JSONArray jsonArray1 = jo.getJSONArray("stations");
						for (int j = 0; j < jsonArray1.length(); j++) {
							JSONObject jo1 = jsonArray1.getJSONObject(j);
							jsonAll.put(jo1);
							TreeBean treeBean1 = new TreeBean();
							treeBean1.setId(jo1.getInt("stationNo"));
							treeBean1.setName(jo1.getString("stationName"));
							saveRecentSearchHistory(jo1
									.getString("stationName"));
							stations[i][j] = treeBean1;
						}

					}
					sbStations = jsonAll.toString();

					return true;
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				closeProgressBar();
				if (result) {

					adapter.RemoveAll();
					adapter.notifyDataSetChanged();

					List<TreeViewAdapter.TreeNode> treeNode = adapter
							.GetTreeNode();
					for (int i = 0; i < districts.length; i++) {
						TreeViewAdapter.TreeNode node = new TreeViewAdapter.TreeNode();
						node.parent = ((TreeBean) districts[i]).getName();
						for (int ii = 0; ii < stations[i].length; ii++) {
							if (stations[i][ii] != null) {
								node.childs.add(((TreeBean) stations[i][ii])
										.getName());
							}
						}
						treeNode.add(node);
					}

					adapter.UpdateTreeNode(treeNode);
					expandableList.setAdapter(adapter);
					expandableList
							.setOnChildClickListener(new OnChildClickListener() {

								@Override
								public boolean onChildClick(
										ExpandableListView arg0, View arg1,
										int parent, int children, long arg4) {

									Intent mainIntent = new Intent(
											DataActivity.this,
											DevListActivity.class);
									Bundle bundle = new Bundle();
									bundle.putInt(
											"stationId",
											((TreeBean) stations[parent][children])
													.getId());
									bundle.putString(
											"stationName",
											((TreeBean) stations[parent][children])
													.getName());
									mainIntent.putExtras(bundle);

									startActivity(mainIntent);

									return false;
								}
							});

				} else {
					Toast.makeText(DataActivity.this, "数据加载失败！",
							Toast.LENGTH_SHORT).show();
				}

			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showProgressBar();
			}

		}.execute();

	}

	public void showProgressBar() {
		AnimationSet set = new AnimationSet(true);

		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(500);
		set.addAnimation(animation);

		animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				-1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		animation.setDuration(500);
		set.addAnimation(animation);

		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.5f);
		RelativeLayout loading = (RelativeLayout) findViewById(R.id.loading);
		loading.setVisibility(View.VISIBLE);
		loading.setLayoutAnimation(controller);
	}

	public void closeProgressBar() {

		AnimationSet set = new AnimationSet(true);

		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(500);
		set.addAnimation(animation);

		animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				0.0f, Animation.RELATIVE_TO_SELF, -1.0f);
		animation.setDuration(500);
		set.addAnimation(animation);

		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.5f);
		RelativeLayout loading = (RelativeLayout) findViewById(R.id.loading);

		loading.setLayoutAnimation(controller);

		loading.setVisibility(View.INVISIBLE);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// doExit();
			this.finish();
			nm.notify(notification_id, notification);

			// this.startService(new Intent(this, AlarmService.class));

			return false;
		}
		return false;
	}

	// 显示一个通知
	private void showNotification() {
		// 创建一个通知
		Notification mNotification = new Notification();

		// 设置属性值
		mNotification.icon = R.drawable.icon;
		mNotification.tickerText = "NotificationTest";
		mNotification.when = System.currentTimeMillis(); // 立即发生此通知

		// 带参数的构造函数,属性值如上
		// Notification mNotification = = new
		// Notification(R.drawable.icon,"NotificationTest",
		// System.currentTimeMillis()));

		// 添加声音效果
		mNotification.defaults |= Notification.DEFAULT_SOUND;

		// 添加震动,由于在我的真机上会App发生异常,估计是Android2.2里的错误,略去，不添加
		// mNotification.defaults |= Notification.DEFAULT_VIBRATE ;

		// 添加状态标志

		// FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉
		// FLAG_NO_CLEAR 该通知能被状态栏的清除按钮给清除掉 75. //FLAG_ONGOING_EVENT 通知放置在正在运行
		// 76. //FLAG_INSISTENT 通知的音乐效果一直播放
		mNotification.flags = Notification.FLAG_INSISTENT;

		// 设置setLatestEventInfo方法,如果不设置会App报错异常
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// 注册此通知
		// 如果该NOTIFICATION_ID的通知已存在，不会重复添加，只是播放相应的效果(声音等)

		mNotificationManager.notify(NOTIFICATION_ID, mNotification);

	}

	private void removeNotification() {
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// 取消的只是当前Context的Notification
		mNotificationManager.cancel(NOTIFICATION_ID);
	}

	private void initNoti() {
		nm = (NotificationManager) this
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification(R.drawable.icon48, "",
				System.currentTimeMillis());
		notification.contentView = new RemoteViews(getPackageName(),
				R.layout.notification);
		// notification.contentView.setProgressBar(R.id.pb, 100, 0, false);

		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		notification.contentIntent = contentIntent;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menudata, menu);// 指定使用的XML
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int item_id = item.getItemId();// 得到当前选中MenuItem的ID
		switch (item_id) {
		case R.id.search: {
			onSearchRequested();
			break;
		}
		case R.id.relogin: {
			login();
			break;
		}
		case R.id.refresh: {
			adapter.RemoveAll();
			adapter.notifyDataSetChanged();
			showProgressBar();
			new Thread() {
				public void run() {
					try {
						User user = DataService.queryUser(DataActivity.this);
						userId = user.getUserId();
						result = HttpGet.getResult("http://" + ipStr
								+ "/andriod!findDistrictAndStation.do?userId="
								+ userId, DataActivity.this, "utf8");
						Log.v("dpc", result);
						DataService.deleteData(DataActivity.this, userId);
						DataService.insertData(DataActivity.this, userId,
								result);
						m_handlerRefresh.sendEmptyMessage(0);
					} catch (Exception e) {
						Log.v("dpcError",
								e.getLocalizedMessage() + " " + e.getMessage());
						e.printStackTrace();
					}
				}
			}.start();
			break;
		}
		case R.id.exit: {
			this.finish();
			break;
		}
		}
		return super.onOptionsItemSelected(item);
	}

	private Handler m_handlerRefresh = new Handler() {
		public void handleMessage(Message msg) {
			try {
				showList();
			} catch (Exception e) {
				Log.v("dpcError",
						e.getLocalizedMessage() + " " + e.getMessage());
				e.printStackTrace();
			}
		}
	};

	// 保存最近搜索的关键字记录
	private void saveRecentSearchHistory(String queryKeyword) {
		SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
				SearchSuggestionSampleProvider.AUTHORITY,
				SearchSuggestionSampleProvider.MODE);
		suggestions.saveRecentQuery(queryKeyword, null);
	}

	@Override
	public boolean onSearchRequested() {
		Bundle bundle = new Bundle();
		bundle.putString("data", sbStations);
		// 打开浮动搜索框（第一个参数默认添加到搜索框的值）
		// bundle为传递的数据
		startSearch("", false, bundle, false);
		// 这个地方一定要返回真 如果只是super.onSearchRequested方法不但　　　　
		// //onSearchRequested（搜索框默认值）无法添加到搜索框中,bundle也无法传递出去
		return true;
	}

	private void login() {
		AlertDialog.Builder ad = new AlertDialog.Builder(this);
		ad.setTitle("切换账户");
		View view = View.inflate(this, R.layout.login, null);
		EditText passwordEt = (EditText) view.findViewById(R.id.txt_password);
		EditText userEt = (EditText) view.findViewById(R.id.txt_username);
		EditText ipEt = (EditText) view.findViewById(R.id.ipname);
		User user = DataService.queryUser(DataActivity.this);
		if (user != null) {
			passwordEt.setText(user.getPassword());
			userEt.setText(user.getUserId());
			ipEt.setText(user.getIp());
		}

		ad.setView(view);
		registerdialog = ad.create();

		registerdialog.setButton("登录",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						EditText passwordEt1 = (EditText) registerdialog
								.findViewById(R.id.txt_password);
						EditText userEt1 = (EditText) registerdialog
								.findViewById(R.id.txt_username);
						EditText ipEt1 = (EditText) registerdialog
								.findViewById(R.id.ipname);

						ipStr = ipEt1.getText().toString();
						userId = userEt1.getText().toString();
						password = passwordEt1.getText().toString();

						try {
							Field field = registerdialog.getClass()
									.getSuperclass()
									.getDeclaredField("mShowing");
							field.setAccessible(true);
							field.set(registerdialog, true);
						} catch (Exception e) {
							e.printStackTrace();
						}

						if (ipStr.equals("") || userId.equals("")
								|| password.equals("")) {
							try {
								Field field = registerdialog.getClass()
										.getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(registerdialog, false);
							} catch (Exception e) {
								e.printStackTrace();
							}

							registerdialog.findViewById(R.id.txt_loginerror)
									.setVisibility(View.VISIBLE);
							return;
						}

						// 生成注册对话框
						m_Dialog = ProgressDialog.show(DataActivity.this,
								"请等待...", "正在登录...", true, true);

						new Thread() {
							public void run() {
								try {
									result = HttpGet.getResult("http://"
											+ ipStr + "/andriod!isExsit.do?u="
											+ userId + "&p=" + password,
											DataActivity.this, "utf8");
									if (result.trim().equals("1")) {
										User user = new User();
										user.setIp(ipStr);
										user.setUserId(userId);
										user.setPassword(password);
										DataService
												.deleteUser(DataActivity.this);
										DataService.insertUser(
												DataActivity.this, user);
										m_handlerLoginSuc.sendEmptyMessage(0);
									} else {
										m_handlerLoginFail.sendEmptyMessage(0);
									}

								} catch (Exception e) {
									e.printStackTrace();
									// m_handlerLoginFail.sendEmptyMessage(0);
								}
							}
						}.start();

					}
				});
		registerdialog.setButton2("关闭",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						registerdialog.dismiss();
						// MainActivity.this.finish();
					}
				});
		registerdialog.show();
	}

	private Handler m_handlerLoginSuc = new Handler() {
		public void handleMessage(Message msg) {
			// m_progressDlg.hide();
			try {
				m_Dialog.dismiss();
				// 提示登录成功
				Toast.makeText(DataActivity.this, "登录成功，加载用户数据中...",
						Toast.LENGTH_SHORT).show();
				// 转到主题页面
				// adapter.RemoveAll();
				// adapter.notifyDataSetChanged();
				// showProgressBar();

				initData();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private Handler m_handlerLoginFail = new Handler() {
		public void handleMessage(Message msg) {
			// m_progressDlg.hide();
			try {
				m_Dialog.dismiss();
				// 提示登录不成功
				registerdialog.show();
				registerdialog.findViewById(R.id.txt_loginerror).setVisibility(
						View.VISIBLE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private void initData() {
		new Thread() {
			public void run() {
				try {
					result = HttpGet.getResult("http://" + ipStr
							+ "/andriod!findDistrictAndStation.do?userId="
							+ userId, DataActivity.this, "utf8");
					Log.v("dpc", result);
					DataService.deleteData(DataActivity.this, userId);
					DataService.insertData(DataActivity.this, userId, result);
					m_handler.sendEmptyMessage(0);
				} catch (Exception e) {
					Log.v("dpcError",
							e.getLocalizedMessage() + " " + e.getMessage());
					e.printStackTrace();
				}
			}
		}.start();
	}

	// private void initData() {
	// new Thread() {
	// public void run() {
	// try {
	// result = HttpGet.getResult("http://" + ipStr
	// + "/districtAction!findAll.do", DataActivity.this,
	// "utf8");
	// Log.v("dpc", result);
	// m_handler.sendEmptyMessage(0);
	// } catch (Exception e) {
	// Log.v("dpcError",
	// e.getLocalizedMessage() + " " + e.getMessage());
	// e.printStackTrace();
	// }
	// }
	// }.start();
	// }

	private Handler m_handler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				showList();
			} catch (Exception e) {
				Log.v("dpcError",
						e.getLocalizedMessage() + " " + e.getMessage());
				e.printStackTrace();
			}
		}
	};
}
